package com.gwm.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gwm.common.enums.ExceptionEnums;
import com.gwm.common.exceptions.LyException;
import com.gwm.common.utils.BeanHelper;
import com.gwm.common.vo.PageResult;
import com.gwm.item.dto.BrandDTO;

import com.gwm.item.service.TbBrandService;
import com.gwm.item.service.TbCategoryBrandService;
import com.gwm.item.mapper.TbBrandMapper;
import com.gwm.item.pojo.TbBrand;
import com.gwm.item.pojo.TbCategoryBrand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author heima
 * @since 2020-12-01
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {

    @Override
    public PageResult<BrandDTO> findByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
//        select * from tb_brand where name like '%key%' or letter='key' order by 'sortBy' 'desc' limit (page-1)*rows,rows
        QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){ //如果key不为空 开始拼凑条件
            queryWrapper.lambda().like(TbBrand::getName,key);
            queryWrapper.or().lambda().eq(TbBrand::getLetter,key);
        }
        if(StringUtils.isNotEmpty(sortBy)){  //如果排序字段sortby不为空 开始拼凑条件
            if(desc){
                queryWrapper.orderByDesc(sortBy);
            }else{
                queryWrapper.orderByAsc(sortBy);
            }
        }
//        分页的条件
        Page<TbBrand> page1 = new Page<>(page,rows);

        IPage<TbBrand> page2 = this.page(page1, queryWrapper);
        /*List<TbBrand> records = page2.getRecords();//当前页数据集合
        page2.getTotal(); //总条数
        page2.getPages(); //总页数*/
        if(page2==null|| CollectionUtils.isEmpty(page2.getRecords())){
            throw new LyException(ExceptionEnums.BRAND_NOT_FOUND);
        }
//        Long total, Long totalPage, List<T> items
        return new PageResult(page2.getTotal(),page2.getPages(), BeanHelper.copyWithCollection(page2.getRecords(),BrandDTO.class));
    }


    @Autowired
    private TbCategoryBrandService categoryBrandService;

    @Override
    @Transactional
    public void saveBrandAndCategory(BrandDTO brandDTO, List<Long> cids) {
//        保存品牌数据和 品牌分类的关联表数据
        TbBrand tbBrand = BeanHelper.copyProperties(brandDTO, TbBrand.class);
//        boolean insert = tbBrand.insert();
        boolean isSave = this.save(tbBrand);
        if(!isSave){
            throw new LyException(ExceptionEnums.INSERT_OPERATION_FAIL);
        }
//        保存 品牌分类的关联表数据
        for (Long cid : cids) {
            TbCategoryBrand categoryBrand = new TbCategoryBrand();
            categoryBrand.setBrandId(tbBrand.getId());
            categoryBrand.setCategoryId(cid);
//            categoryBrand.insert();
            categoryBrandService.save(categoryBrand);
        }
//        insert into tb_category_brand (category_id,brand_id) values(cid,brandId)
    }

    @Override
    @Transactional
    public void updateBrandAndCategory(BrandDTO brandDTO, List<Long> cids) {
//        1、修改品牌数据
        //        保存品牌数据和 品牌分类的关联表数据
        TbBrand tbBrand = BeanHelper.copyProperties(brandDTO, TbBrand.class);
//        boolean insert = tbBrand.updateById();
        boolean isUpdate = this.updateById(tbBrand);
        if(!isUpdate){
            throw new LyException(ExceptionEnums.UPDATE_OPERATION_FAIL);
        }
//        delete from tb_category_brand where brand_id=?

        //        2、删除当前品牌之前的分类数据  删除中间表
        QueryWrapper<TbCategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbCategoryBrand::getBrandId,tbBrand.getId());
        boolean isRemove = categoryBrandService.remove(queryWrapper);
        if(!isRemove){
            throw new LyException(ExceptionEnums.UPDATE_OPERATION_FAIL);
        }
//        3、保存 品牌分类的关联表数据
        for (Long cid : cids) {
            TbCategoryBrand categoryBrand = new TbCategoryBrand();
            categoryBrand.setBrandId(tbBrand.getId());
            categoryBrand.setCategoryId(cid);
//            categoryBrand.insert();
            categoryBrandService.save(categoryBrand);
        }
    }

    @Override
    public List<BrandDTO> findBrandListByCategoryId(Long categoryId) {
        List<TbBrand> tbBrandList = this.getBaseMapper().findBrandListByCategoryId(categoryId);
        if( CollectionUtils.isEmpty(tbBrandList)){
            throw new LyException(ExceptionEnums.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(tbBrandList,BrandDTO.class);
    }
}
